/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SimplexVisao.java
 *
 * Created on 16/06/2012, 03:12:47
 */
package Visao;

import Processamento.MetodosSimplex;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author magelinha
 */
public class SimplexVisao extends javax.swing.JFrame {

    DefaultTableModel modelo;
    MetodosSimplex metodos = new MetodosSimplex();
    File arquivo;
    DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");
    public static List<Integer> pivos = new ArrayList<Integer>();
    public static boolean multiplasSolucoes = false;
    public boolean processoFinalizado = false;
    public static List<List<Double>> listaMultiplasSolucoes = new ArrayList<List<Double>>();
    double[][] matrizCopia;
    
    /**
     * Método que faz a busca do arquivo
     */
    public void procurarArquivo(){
        JFileChooser procurar = new JFileChooser();
        int retorno = procurar.showOpenDialog(this);
        
        if(retorno == JFileChooser.APPROVE_OPTION){
            arquivo = procurar.getSelectedFile();
            jTArquivo.setText(arquivo.getAbsolutePath());
        }
    }
    
    public void editarTabela(){
        modelo = (DefaultTableModel) jTableTableu.getModel();
        
        modelo.setNumRows(0);
        modelo.setColumnCount(MetodosSimplex.quantidadeVariaveis + MetodosSimplex.folga + 3);
        modelo.setRowCount(MetodosSimplex.quantidadeRestricoes + 2);
        centralizarDados();
        
        for(int i=0; i < modelo.getColumnCount(); i++){
            jTableTableu.getColumnModel().getColumn(i).setHeaderValue(" ");
        }
    }
    
    public void centralizarDados(){
        DefaultTableCellRenderer centralizar = new DefaultTableCellRenderer();
        centralizar.setHorizontalAlignment(SwingConstants.CENTER);
        
        for(int i=0; i< modelo.getColumnCount();i++){
            jTableTableu.getColumnModel().getColumn(i).setCellRenderer(centralizar);
        }
    }
    
    public void inserirVariaveisNaTabela(){
        for(int i=1;i<modelo.getColumnCount();i++){
            modelo.setValueAt(MetodosSimplex.vetorVariaveis.get(i-1), 0, i);
        }
        
        for(int i=1;i<modelo.getRowCount();i++){
            modelo.setValueAt(MetodosSimplex.vetorFolga.get(i-1), i, 0);
        }
    }
    
    public void preencherTabela(){
        editarTabela();
        inserirVariaveisNaTabela();
        for(int i=1; i< MetodosSimplex.quantidadeRestricoes+2; i++){
            for(int j=1; j <= MetodosSimplex.quantidadeVariaveis + MetodosSimplex.folga + 2; j++){
                modelo.setValueAt(decimalFormat.format(MetodosSimplex.matrizSimplex[i-1][j-1]), i, j);
            }
        }
    }
    
    public boolean escolherPivo(){
        pivos = metodos.escolherPivo();
        if(pivos.size() == 1 && pivos.get(0) == -1){
            return false;
        }else if(pivos.isEmpty()){
            pivos = metodos.verificarMultiplasSolucoes();
            
            if(pivos.isEmpty()) return false;
            MetodosSimplex.preencherListResultado();
            listaMultiplasSolucoes.add(metodos.copiarVetorResultado());
            
            multiplasSolucoes = true;
        }
        
        jTColuna.setText(String.valueOf(pivos.get(0)));
        jTLinha.setText(String.valueOf(pivos.get(1)));
        jTValor.setText(decimalFormat.format(MetodosSimplex.matrizSimplex[pivos.get(1)][pivos.get(0)]));
        inserirOperacoesNoTextArea(pivos.get(1), pivos.get(0));
        MetodosSimplex.alterarBase(pivos.get(1), pivos.get(0));
        return true;
        
    }
    
    public void operacoes(){
        
    }
    
    public void executar(){
        try {
            processoFinalizado = false;
            multiplasSolucoes = false;
            jBProximoPasso.setEnabled(true);
            metodos.lerArquivo(arquivo);
            preencherTabela();
            matrizCopia = metodos.copiarMatrizInicial();
            
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(null, "Arquivo não encontrado!");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Erro ao abrir o arquivo!");
        }
    }
    
    public void inserirOperacoesNoTextArea(int linha, int coluna){
        jAreaOperacoes.setText("");
        for(String item: metodos.operacoesEntreLinhas(linha, coluna)){
            jAreaOperacoes.append(item + "\n");
        }
    }
    
    public void proximoPasso(){
        if(escolherPivo()){
            preencherTabela();
        }else {
            if(!pivos.isEmpty()){
                JOptionPane.showMessageDialog(null, "Processo finalizado - Solução Ilimitada");
                jAreaOperacoes.setText("Problema Ilimitado");
                processoFinalizado = true;
                jBProximoPasso.setEnabled(false);
                
            }else{
                JOptionPane.showMessageDialog(null, "Processo finalizado");
                imprimirResultado();
                processoFinalizado = true;
                jBProximoPasso.setEnabled(false);
            }
            
        }
    }
    
    public void imprimirResultado(){
        jAreaOperacoes.setText("Resultado: \n\n");
        
        jAreaOperacoes.append("Base: ");
        jAreaOperacoes.append(metodos.toString() + "\n");
        
        
        jAreaOperacoes.append("z = " + decimalFormat.format(
                MetodosSimplex.matrizSimplex[0][MetodosSimplex.quantidadeVariaveis + MetodosSimplex.folga+1] * (-1)));
    }
    
    
    /** Creates new form SimplexVisao */
    public SimplexVisao() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTArquivo = new javax.swing.JTextField();
        jBProcurar = new javax.swing.JButton();
        jBExecutar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableTableu = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jTLinha = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTColuna = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTValor = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jAreaOperacoes = new javax.swing.JTextArea();
        jBProximoPasso = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Selecione o arquivo de entrada"));

        jLabel1.setText("Arquivo");

        jBProcurar.setText("Procurar");
        jBProcurar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBProcurarActionPerformed(evt);
            }
        });

        jBExecutar.setText("Executar");
        jBExecutar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBExecutarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, 423, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jBProcurar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jBExecutar)
                .addContainerGap(136, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBProcurar)
                    .addComponent(jBExecutar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTableTableu.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableTableu.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTableTableu);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Pivo"));

        jLabel2.setText("Linha");

        jLabel3.setText("Coluna");

        jLabel4.setText("Valor");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTLinha, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTColuna, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTValor, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(jTValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jTLinha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3)
                        .addComponent(jTColuna, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(12, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Operações"));

        jAreaOperacoes.setColumns(20);
        jAreaOperacoes.setRows(5);
        jScrollPane2.setViewportView(jAreaOperacoes);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2)
        );

        jBProximoPasso.setText("Próximo Passo");
        jBProximoPasso.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBProximoPassoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(12, 12, 12))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jBProximoPasso)
                .addGap(344, 344, 344))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(18, 18, 18)
                .addComponent(jBProximoPasso)
                .addContainerGap(51, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jBProcurarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBProcurarActionPerformed
        procurarArquivo();
    }//GEN-LAST:event_jBProcurarActionPerformed

    private void jBExecutarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBExecutarActionPerformed
        executar();
    }//GEN-LAST:event_jBExecutarActionPerformed

    private void jBProximoPassoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBProximoPassoActionPerformed
        proximoPasso();
    }//GEN-LAST:event_jBProximoPassoActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SimplexVisao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SimplexVisao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SimplexVisao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SimplexVisao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new SimplexVisao().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea jAreaOperacoes;
    private javax.swing.JButton jBExecutar;
    private javax.swing.JButton jBProcurar;
    private javax.swing.JButton jBProximoPasso;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTArquivo;
    private javax.swing.JTextField jTColuna;
    private javax.swing.JTextField jTLinha;
    private javax.swing.JTextField jTValor;
    private javax.swing.JTable jTableTableu;
    // End of variables declaration//GEN-END:variables
}
